import mx.utils.Delegate;
import mx.xpath.XPathAPI;
import mx.events.EventDispatcher;
import com.live5.liveplayer.MediaItem;

class com.live5.liveplayer.Playlist
{
	private var PlType:String;
	private var MediaList:Array;
	private var current:MediaItem;
	private var next:MediaItem;
	private var prev:MediaItem;
	private var currentIndex:Number=-1;
	private var xmlDoc:XML;
	private var autoLoop:Boolean;
	//private var dispatchEvent:Function;
	public function addEventListener(type:String,target:Function):Void{};
	public function removeEventListener(type:String,target:Function):Void{};
	public var dispatchEvent:Function;

	function Playlist(plPath:String,plType:String)
	{
		PlType=plType;
		EventDispatcher.initialize(this);
		MediaList =new Array();
		xmlDoc=new XML();
		xmlDoc.ignoreWhite=true;
		xmlDoc.onLoad=Delegate.create(this,XmlDocOnLoad);
		xmlDoc.load(plPath);
	}
	function ParsePL(xmlDoc:XML){
		if(PlType=="rss"){
			var items:Array =XPathAPI.selectNodeList(xmlDoc.firstChild,"/rss/channel/item");
			
			for(var i:Number=0;i<items.length;i++){
				
				var enclosure:XMLNode = XPathAPI.selectSingleNode(items[i],"item/enclosure");
				var type:String =enclosure.attributes["type"];
				var url:String = enclosure.attributes["url"];
				var mediaItem:MediaItem=new MediaItem(type,url);
				MediaList.push(mediaItem);
			}
		}
		if(PlType=="atom"){
			var items:Array =XPathAPI.selectNodeList(xmlDoc.firstChild,"/feed/entry");
			
			for(var i:Number=0;i<items.length;i++){
				
				var enclosure:XMLNode = XPathAPI.selectSingleNode(items[i],"entry/content");
				var type:String =enclosure.attributes["type"];
				var url:String = enclosure.attributes["src"];
				var mediaItem:MediaItem=new MediaItem(type,url);
				MediaList.push(mediaItem);
			}
		}
	    OnLoaded();
	}
	function XmlDocOnLoad(){
		ParsePL(xmlDoc);
	}
	
	[Event("loaded")]
	function OnLoaded():Void{
		var eventObj = new Object();
        eventObj.type = "loaded";
        eventObj.target = this;
		this.dispatchEvent(eventObj);
	}
	
	function get Current():MediaItem{
		if(currentIndex!=-1){
			return MediaList[currentIndex];
		}
		else{
			return null;
		}
		
	}
	function get Next():MediaItem{
		
		if(currentIndex < MediaList.length-1){
			return MediaList[currentIndex+1];
		}else{
			return null;
		}
	}

	function get Prev():MediaItem{
		if(currentIndex>0){
			return MediaList[currentIndex-1];
		}else{
			return null;
		}
	}
	function get Count():Number{
		return MediaList.length;
	}
	function MoveNext():MediaItem{
		if(currentIndex < MediaList.length-1){
		}
			currentIndex++;
		return Current;
	}
	function MovePrev():MediaItem{
		if(currentIndex>0){
			currentIndex--;
		}
		return Current;
	}
}
